<template>
  <div>
    <Row :gutter="24" class="mb-5">
      <Col :span="12">
        <a-button type="primary" @click="batchAdd(spec)">添加商品规格</a-button>
        <!-- <FormItem label="规格名称" :rules="[{ required: false }]">
          <a-input v-model:value="model.skus"/>
        </FormItem> -->
      </Col>
    </Row>
    <div v-for="(item, index) in spec" :key="index" style="background-color: #f5f5f5;" class="p-4 pb-0 mb-4">   
      <Row :gutter="24">
        <Col :span="22" >
          <FormItem label="规格名称" :rules="[{ required: false }]">
            <a-input v-model:value="item.name" placeholder="例：如颜色" style="width:30%" />
          </FormItem>
          <Row :gutter="24">
            <Col :span="4" class="pl-2" v-for="(va,idx) in item.value">
              <FormItem :rules="[{ required: false }]">
                <div class="position:relative">
                  <a-input v-model:value="item.value[idx]"  placeholder="请输入规格值" />
                  <Icon v-if="idx>0" @click="() => delValue(item.value,idx)" style="position:absolute;top:-5px;right:-3px;cursor:pointer" icon="ant-design:close-circle-filled" :size="15" />
                </div>
              </FormItem>
            </Col>
            <Col :span="2" class="pl-2">
              <a-button danger  @click="() => addValue(item.value)">添加规格值</a-button>
            </Col>
          </Row>
        </Col>
        <Col :span="2" >
          <a-button danger  @click="() => delAttr(spec,index)">删除</a-button>
        </Col>
      </Row>
    </div>
    <div v-if="state.skus.length>0 && spec.length>0">
      <p>批量操作 
        <a-button size="small" class="ml-2" @click="handleCreatePrompt('no')">设置货号</a-button>
        <a-button size="small" class="ml-2" @click="handleCreatePrompt('price')">销售价格</a-button>
        <a-button size="small" class="ml-2" @click="handleCreatePrompt('marketprice')">市场价格</a-button>
        <a-button size="small" class="ml-2" @click="handleCreatePrompt('costprice')">成本价格</a-button>
        <a-button size="small" class="ml-2" @click="handleCreatePrompt('weight')">设置重量</a-button>
        <a-button size="small" class="ml-2" @click="handleCreatePrompt('inventory')">设置库存</a-button>
      </p>
      <table class="mstable table" width="100%">
        <thead>
          <tr>
            <th width="120" align="left" v-for="item in spec.map(q=>{return q.name})">{{ item }}</th>
            <th>商品货号</th>
            <th>销售价格</th>
            <th>市场价格</th>
            <th>成本价格</th>
            <th>重量(克)</th>
            <th>库存</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in state.skus">
            <td class="mr-10" v-for="attr in spec.map(q=>{return q.name})">{{ item[attr] }}</td>
            <td> <FormItem :rules="[{ required: false }]"><a-input v-model:value="item.no" /></FormItem></td>
            <td> <FormItem :rules="[{ required: false }]"><a-input v-model:value="item.price"/></FormItem></td>
            <td> <FormItem :rules="[{ required: false }]"><a-input v-model:value="item.marketprice" /></FormItem></td>
            <td> <FormItem :rules="[{ required: false }]"><a-input v-model:value="item.costprice"/></FormItem></td>
            <td> <FormItem :rules="[{ required: false }]"><a-input v-model:value="item.weight" /></FormItem></td>
            <td> <FormItem :rules="[{ required: false }]"><a-input v-model:value="item.inventory" /></FormItem></td>
          </tr>
        </tbody>
      </table>
    </div>

  </div>
</template>
<script lang="ts" setup>
  import { defineProps, defineEmits,reactive, watch } from 'vue';
  import { Row, Col,FormItem, message } from 'ant-design-vue';
  import Icon from '@/components/Icon/Icon.vue';
  import { createPrompt } from '@/components/Prompt';
  import { nextTick } from 'vue';

  defineOptions({ name: 'GoodsAttr' });
  const props = defineProps<{
    spec: any,
    skus: any
  }>();

  const state = reactive({skus: []});

  const emit = defineEmits(['success']);

  //笛卡尔积
  function cartesianProduct(arrays) {  
    function combine(arr, index) {  
      if (index === arr.length) {  
        return [{}];  
      }  
      let rest = combine(arr, index + 1);  
      let result = [];  
      for (let i = 0; i < arr[index].value.length; i++) {  
          for (let j = 0; j < rest.length; j++) {  
              let current = { ...rest[j] }; // 复制当前组合  
              current[arr[index].name] = arr[index].value[i]; // 添加当前元素的name和value  
              result.push(current);  
          }  
      }  
      return result;  
    }  

    // let values = arrays.map(obj => obj.value);  
    // let initial = [{}];  
    // 调用辅助函数并返回结果  
    return combine(arrays, 0).map(combo => {  
        // 如果需要，可以在这里对结果进行进一步的处理或格式化  
        return combo;  
    }); 
  } 

    // 辅助函数，用于将对象转换为字符串键（假设所有键都是字符串）  
  function objToKey(obj,q) {  
    return Object.keys(obj).sort().filter(key=>q.indexOf(key)>-1).map(key => `${key}:${obj[key]}`).join('|');  
  }  
    
  watch(props, (a,b)=>{
    nextTick(() => {
      const pres = props.spec.map(s=> s.name);
      const proSpec = cartesianProduct(a.spec);
      // 用于存储完整SKU的数组  
      const completeSkus = [];  
      // 遍历proSpec，尝试与skus匹配  
      proSpec.forEach(spec => {  
        const specKey = objToKey(spec,pres);  
        const matchingSku = props.skus.find(sku => objToKey(sku,pres) === specKey);  
        if (matchingSku) {  
            // 如果找到匹配的SKU，则将其添加到completeSkus中  
            completeSkus.push(matchingSku);  
        } else {  
          // 如果没有找到匹配的SKU，则创建一个新的SKU对象并添加到completeSkus中  
          // 这里我们使用默认值来填充缺失的属性  
          // const newSku = {...spec};  
          completeSkus.push(spec);  
        }  
      });  
      //与skus 传递的值比对
      state.skus = completeSkus;
    });
  });

  watch(state, (a,b)=>{
    nextTick(() => {
      emit('success', state.skus);
    });
  });

  function batchAdd(item) {
    item.push({ name: '', value: [''] });
  }

  function delValue(item,field: number){
    item.splice(field, 1);
  }

  function addValue(item){
    item.push('');
  }

  function delAttr(item,field: number) {
    item.splice(field, 1);
  }
  
  function handleCreatePrompt(type) {
    let title = '';
    switch(type) {
      case 'no':title='货号';break;
      case 'price':title='销售价格';break;
      case 'marketprice':title='市场价格';break;
      case 'costprice':title='成本价格';break;
      case 'weight':title='重量';break;
      case 'inventory':title='库存';break;
    }
    createPrompt({
      title: '请设置'+ title,
      required: true,
      label: title,
      defaultValue: '',
      onOK: async (value: string) => {
        message.success('设置'+ title+"成功");
        state.skus.map(w => {
          w[type] = value;
        });
      },
      inputType: 'Input',
    });
  }
</script>

<style >
 .mstable.table, .mstable.table th, .mstable.table td {
    padding: 8px;
    border-collapse: collapse; /* 移除双边框 */
    border: 1px solid #ccc;
  }

  .mstable.table th{
    background-color: #ddd;
  }
</style>